package com.dyt.itool.parser;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.dyt.itool.util.ByteBuffer;
import com.dyt.itool.util.FileUtils;


public class TextParser {
	
	private static Logger logger = Logger.getLogger( TextParser.class );

	private class Text{
		private String key;
		private String value;
		
		public Text( String key, String value ){
			this.key = key;
			this.value = value;
		}
	}
	
	private Map<String, List<Text> > languageMap = new HashMap<String, List<Text> >();
	
	public void parseDir( String dirName ){
	
		File dir = new File( dirName );
		if( !dir.exists() || !dir.isDirectory( ) ){
			logger.debug( "要解析的文件夹不存在" );
			return;
		}
		
		File[] fileList = dir.listFiles();
		for( File file : fileList ){
			parseFile( file );
		}
	}
	
	public void generateBin( String outputDir  ){
		
		
		Set<String> keys = languageMap.keySet();
		for( String language : keys ){

			File dir = new File( outputDir , language );
			if( !dir.exists( ) ){
				dir.mkdirs( );
			}
			
			List<Text> textList = languageMap.get( language );
			
			ByteBuffer buffer = new ByteBuffer();		
			buffer.writeInt( textList.size() );
			for( Text text : textList ){
				buffer.writeUTF8( text.key );
				buffer.writeUTF8( text.value );
			}
			
			FileUtils.writeFile( new File( dir, "text.bin"), buffer.array()  );
		}
		
	}
	
	
	
	public void parseFile( File file ){
		logger.info( "parse file " + file.getName() );
		if( !file.exists()  || !file.isFile( ) ){
			logger.debug( "要解析的文件不存在" );
			return;
		}
		
		if( file.getName().startsWith( ".") ||  file.getName().startsWith("~") ){
			logger.debug( "无法解析的文件名:" +  file.getName() );
			return;
		}
		
		if(  !file.getName().endsWith( ".xls")  && !file.getName().endsWith( ".xlsx") ){
			logger.debug( "无法解析的文件名:" +  file.getName() );
			return;
		}
		
		

		Workbook wb = null;
		
		try{
			if( file.getName().endsWith( "xls")  ){
				wb = new HSSFWorkbook(  new FileInputStream( file )   );
			}else if( file.getName().endsWith( "xlsx")){
				wb = new XSSFWorkbook(  new FileInputStream( file )  );
			}	
		}catch( Exception e ){
			e.printStackTrace( );
			
			logger.debug( e.getMessage( ) );
			return;
		}
		
		parseTextFile( wb );
	}
	
	
	private void parseTextFile( Workbook  wb ){
		Sheet sheet = wb.getSheetAt( 0 );	    
		Row rowType = sheet.getRow( 0 );
	    Row rowName = sheet.getRow( 1 ); 
	    int columnSize = rowType.getPhysicalNumberOfCells( );
	    int rowSize = sheet.getPhysicalNumberOfRows( );
	    
	    int languageColumnStart = 2; //从简体中文开始算
	    int languageColumnChinese = 2; //简体中文列
	    int languageColumnKey = 1; //ID列
	    
	    List<String> languageNames = new ArrayList<String>();
	    for( int column = languageColumnStart; column < columnSize; column++ ){
	    	String language = getStringCellValue( rowName.getCell( column ) );
	    	languageNames.add(  language );
	    }
	    
	    for( int rowIndex = 3; rowIndex < rowSize; rowIndex++ ){
			Row row = sheet.getRow( rowIndex );
			if( row == null )
				continue;
			
			String key = getStringCellValue( row.getCell( languageColumnKey ) );
			String chinese = getStringCellValue( row.getCell( languageColumnChinese ) );
			
			 for( int column = languageColumnStart; column < columnSize; column++ ){
			    	String value = getStringCellValue( row.getCell( column ) );
			    	
			    	putText( languageNames.get( column - languageColumnStart ), key, chinese, value );
			 }
	    }
	}
	
	private void putText( String language, String key, String chineseKey, String value ){
		if (value.equals("")) {
			return;
		}
		
		if( !languageMap.containsKey( language ) ){
			languageMap.put( language, new ArrayList<Text>() );
		}
		
		if (key.equals("")) {
			key = chineseKey; //中文为key
		}
		
		List<Text> textList = languageMap.get( language );
		textList.add( new Text( key, value ) );
	}
	
	private String getStringCellValue(Cell cell) {

        if (cell == null){
            return "";
        }
        
        String strCell = "";
        switch (cell.getCellType()) {
        case HSSFCell.CELL_TYPE_STRING:
            strCell = cell.getStringCellValue();
            break;
        case HSSFCell.CELL_TYPE_NUMERIC:
            strCell = String.valueOf(cell.getNumericCellValue());
            break;
        case HSSFCell.CELL_TYPE_BOOLEAN:
            strCell = String.valueOf(cell.getBooleanCellValue());
            break;
        case HSSFCell.CELL_TYPE_BLANK:
            strCell = "";
            break;
        default:
            strCell = "";
            break;
        }
        if (strCell.equals("") || strCell == null) {
            return "";
        }
        
        return strCell.trim( );
    }

	
	
}
